import axios from "axios";
import qs from "qs";
import {storageGet} from "../utils/storage"
  export const http = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 60000,
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
  });
  function request({ url, method = 'GET', params = {} }) {
    return new Promise((resolve, reject) => {

      method = method.toLowerCase();

      const requestBody = method === 'get' ? 'params' : 'data';

      const format = method === 'get' ? params : qs.stringify(params);

      const token = storageGet("token", 'sessionStorage');
      
      token && (http.defaults.headers.common['Authorization'] = token);

      const result = http({ url, method, [requestBody]: format});
      
      result.then(value => resolve(value.data), reason => reject(reason.response.data) );
    });
  }

  export default request;
  